package com.jrx.anytxn.customer.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.customer.dto.coupon.RightsExchangeLogRes;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
import com.jrx.anytxn.customer.mapper.ext.ExtTlRightsExchangeLogMapper;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
import com.jrx.anytxn.param.enums.OrderStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName RightsExchangeLogServiceImpl
 *
 * @author lujianyou
 * @version 1.0
 * @description 权益资格兑换日志服务实现类
 * @date 2021/6/14 11:32
 **/
@Service
public class RightsExchangeLogServiceImpl implements IRightsExchangeLogService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RightsExchangeLogServiceImpl.class);

    @Autowired
    private ExtTlRightsExchangeLogMapper extTlRightsExchangeLogMapper;

    @Autowired
    private ICustomerService customerService;

    @Override
    public void update(TlRightsExchangeLog tlRightsExchangeLog) {
        tlRightsExchangeLog.setRecordVersionNumber(tlRightsExchangeLog.getRecordVersionNumber() == null ? 1 : tlRightsExchangeLog.getRecordVersionNumber() + 1);
        extTlRightsExchangeLogMapper.updateByTenantAndId(tlRightsExchangeLog);
    }

    /**
     * 保存
     *
     * @param tlRightsExchangeLog
     * @return
     */
    @Override
    public int save(TlRightsExchangeLog tlRightsExchangeLog) {
        return extTlRightsExchangeLogMapper.insert(tlRightsExchangeLog);
    }

    /**
     * 获取客户权益资格兑换列表
     *
     * @param userId
     * @param tenantId
     * @param channel
     * @return
     *
     * @throws TxnBizException
     */
    @Override
    public List<RightsExchangeLogRes> listByUserIdAndTenantIdAndChannel(String userId, String tenantId, String channel) throws TxnBizException {
        CmCustomerSecondLevel customer = customerService.getSecondLevelByCondition(userId, channel, tenantId, null);
        if (customer == null) {
            LOGGER.info("根据 userId:{}、channel:{}、tenantId:{} 查询客户二级信息表，查无记录", userId, channel, tenantId);
            throw new TxnBizException(TxnRespCode.NO_DATA);
        }
        List<RightsExchangeLogRes> result = new ArrayList<>(16);
        List<TlRightsExchangeLog> rightsExchangeLogResList = extTlRightsExchangeLogMapper.selectByCustomerIdAndTenantIdAndChannel(customer.getCustomerId(), tenantId, channel);
        if(!rightsExchangeLogResList.isEmpty()){
            BeanUtils.copyList(rightsExchangeLogResList, result, RightsExchangeLogRes.class);
        }
        return result.stream().sorted(Comparator.comparing(RightsExchangeLogRes::getCreateTime).reversed()).collect(Collectors.toList());
    }

    /**
     * 获取权益兑换明细
     *
     * @param tenantId
     * @param orderState
     * @param channel
     * @return
     */
    @Override
    public List<TlRightsExchangeLog> selectByTenantIdAndOrderStateAndChannel(String tenantId, String orderState, String channel) {
        return extTlRightsExchangeLogMapper.selectByTenantIdAndOrderStateAndChannel(tenantId,orderState,channel);
    }

    /**
     * 更新权益兑换明细表
     *
     * @param tenantId
     * @param sceneOrderId
     * @param channel
     * @param customerId
     * @return
     */
    @Override
    public int updateByCustomerIdAndSceneOrderId(String tenantId, String sceneOrderId, String channel, String customerId) {
        String orderStateSuccess = OrderStateEnum.SUCCESS.getCode();
        return extTlRightsExchangeLogMapper.updateByCustomerIdAndSceneOrderId(tenantId,sceneOrderId,channel,customerId, orderStateSuccess);
    }

    /**
     * 批量插入
     *
     * @param exchangeLogList
     * @return
     */
    @Override
    public int insertBatch(List<TlRightsExchangeLog> exchangeLogList) {
        if (exchangeLogList.isEmpty()){
            return 0;
        }
        return extTlRightsExchangeLogMapper.batchInsertSelective(exchangeLogList);
    }

    /**
     * 根基租户号、充值账号、被推荐人customerId、活动id 查询记录
     * @param tenantId
     * @param chargeAccount
     * @param recommended
     * @param activityId
     * @return
     */
    @Override
    public List<TlRightsExchangeLog> listByChargeAccountAndRecommendedAndActivityId(String tenantId, String chargeAccount, String recommended, String activityId) {
        return extTlRightsExchangeLogMapper.selectByChargeAccountAndRecommendedAndActivityId(tenantId,chargeAccount,recommended,activityId);
    }

    @Override
    public List<TlRightsExchangeLog> listByChargeAccountAndRecommendedAndActivityIdAndTenantId(String tenantId, String chargeAccount, String recommended, String activityId) {
        return extTlRightsExchangeLogMapper.selectByChargeAccountAndRecommendedAndActivityIdAndTenantId(tenantId,chargeAccount,recommended,activityId);
    }
    @Override
    public List<TlRightsExchangeLog> listByCustomerIdAndTenantIdAndChannel(String customerId, String tenantId, String channel) {
        return extTlRightsExchangeLogMapper.listByCustomerIdAndTenantIdAndChannel(customerId,tenantId,channel);
    }

    @Override
    public List<TlRightsExchangeLog> listByCustomerPhoneAndRecommended(String tenantId, String customerPhone, String recommended) {
        return extTlRightsExchangeLogMapper.selectByCustomerPhoneAndRecommended(tenantId, customerPhone, recommended);
    }

    /**
     * 根据客户编号，获取最新的若干条兑换记录
     *
     * @param customerId
     * @param tenantId
     * @param channel
     * @param latestRows
     * @return
     */
    @Override
    public List<TlRightsExchangeLog> listLatestLogsByCustomer(String customerId, String tenantId, String channel, int latestRows) {
        if (latestRows <= 0) latestRows = 1;
        return extTlRightsExchangeLogMapper.selectLatestLogsByCustomer(customerId, tenantId, channel, latestRows);
    }

    /**
     * 根据客户信息，查询最新的一条兑换记录
     *
     * @param customerId
     * @param tenantId
     * @param channel
     * @return
     */
    @Override
    public TlRightsExchangeLog findLatestLogByCustomer(String customerId, String tenantId, String channel) {
        List<TlRightsExchangeLog> list = this.listLatestLogsByCustomer(customerId, tenantId, channel, 1);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    /**
     * 根据id和客户信息，查询记录
     *
     * @param id
     * @param customerId
     * @param tenantId
     * @param channel
     * @return
     */
    @Override
    public TlRightsExchangeLog findByIdAndCustomer(Long id, String customerId, String tenantId, String channel) {
        return extTlRightsExchangeLogMapper.selectByIdAndCustomerId(id, customerId, tenantId, channel);
    }

    /**
     * 根据场景订单id以及平台订单id查询订单
     * 场景订单id:scene_order_id
     * 平台订单id：coupon_system_order_id
     * <p>
     * 在卡券系统中，scene_order_id为时间处理后的信息，coupon_system_order_id为卡券明细表中的id
     *
     * @param tenantId
     * @param customerId
     * @param sceneOrderId
     * @param platOrderId
     * @return
     */
    @Override
    public TlRightsExchangeLog findBySceneOrderIdAndPlatOrderId(String tenantId, String customerId, String sceneOrderId, String platOrderId) {
        return extTlRightsExchangeLogMapper.findBySceneOrderIdAndPlatOrderId(tenantId, customerId, sceneOrderId, platOrderId);
    }
}
